package middleware

import (
	"bytes"
	"fmt"
	"io"
	"time"

	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

func AccessLogs() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()
		var reqBodyBytes []byte
		if c.Request.Body != nil {
			reqBodyBytes, _ = io.ReadAll(c.Request.Body) //gin body readed clear
			//c.Request.Body.Close()
		}
		c.Request.Body = io.NopCloser(bytes.NewBuffer(reqBodyBytes))
		blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer = blw
		c.Next()
		endTime := time.Now()
		latencyTime := endTime.Sub(startTime)
		reqMethod := c.Request.Method
		reqUri := c.Request.RequestURI
		statusCode := c.Writer.Status()

		var context = fmt.Sprintf("Url:%s;Method:%s;reqBody:%s;Start:%s;endTime:%s;cost:%0.2f;StatusCode:%d,res:%s",
			reqUri,
			reqMethod,
			string(reqBodyBytes),
			startTime.Format("2006-01-02 15:04:05"),
			endTime.Format("2006-01-02 15:04:05"),
			latencyTime.Seconds(),
			statusCode,
			blw.body.String(),
		)
		stark.Logger.GetBusinessLogger().Infof(c, context)
		//stark.Logger.Infof(c, context)
	}
}
